package bma.common.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import bma.common.langutil.core.ListUtil;
import bma.common.langutil.core.Pager;
import bma.common.langutil.core.PagerResult;

/**
 * 
 * @author guanzhong
 * 
 */
public abstract class HibernateSearch {

	public abstract String hsql(boolean count);

	public abstract void bind(Query q);

	public <TYPE> PagerResult<TYPE> search(Session s, int page, int pageSize,
			Class<TYPE> cls) {
		String hsql2 = hsql(true);
		Query q = s.createQuery("SELECT COUNT(*) " + hsql2);
		bind(q);
		Number c = (Number) q.iterate().next();
		Pager pager = new Pager();
		pager.create(c.intValue(), page, pageSize);
		List<TYPE> result = null;
		if (pager.getTotal() > 0) {
			String hsql = hsql(false);
			q = s.createQuery(hsql);
			bind(q);
			q.setMaxResults(pager.getPageSize());
			q.setFirstResult(pager.getStart());
			return new PagerResult<TYPE>(ListUtil.toList(q.list(), cls), pager);
		} else {
			result = new ArrayList<TYPE>(0);
		}
		return new PagerResult<TYPE>(result, pager);
	}
}
